package com.pisolution.actuator.client;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * 客户端接入监控体系前置条件检测 目前检测的条件如下.
 *
 * <ul>
 *     <li>客户端是否开启监控开关</li>
 *     <li>客户端是否指定监控服务端地址</li>
 * </ul>
 *
 * @author sora
 * @version 0.1.0
 */
public class ActuatorClientEnabledCondition extends SpringBootCondition {
    // -------------------------------------------------------------------------------------------------
    //  条件检测
    // -------------------------------------------------------------------------------------------------

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 1. 获取监控相关配置.
        final ActuatorClientConfig config = new ActuatorClientConfig();
        Binder.get(context.getEnvironment()).bind("pier.actuator.client", Bindable.ofInstance(config));

        // 2. 校验客户端监控是否开启.
        if (!config.isEnabled()) {
            return ConditionOutcome.noMatch(
                "The pier actuator client is disabled since the option 'pier.actuator.client.enabled' is false."
            );
        }

        // 3. 校验客户端是否指定监控服务端地址.
        if (StringUtils.isBlank(config.getUrl())) {
            return ConditionOutcome.noMatch(
                "The pier actuator client is disabled since the option 'pier.actuator.client.url' is blank."
            );
        }

        return ConditionOutcome.match();
    }
}
